package com.atguigu.gmall.common.interceptor.feign.interceptor;

import com.atguigu.gmall.common.constant.RedisConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class MyFeignRequestInterceptor implements RequestInterceptor {

    //每次，web-all远程调用之前，都会创建新request。创建新request之前，允许我们拦截器先改一下
    //发送远程调用的新请求之前，把老请求的一些核心数据设置到请求中。方便远程服务能知道
    @Override
    public void apply(RequestTemplate template) {
        //SpringMVC中有一个 RequestContextHolder；利用ThreadLocal在整个同一线程中共享请求
        //1、拿到当前请求; 异步情况下当前请求获取不到
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();

        //如果不是异步情况下。默认都是能获取到当前请求的
        if(attributes != null){
            //2、获取这个请求
            HttpServletRequest request = attributes.getRequest();

            //3、获取核心请求头
            String userId = request.getHeader(RedisConstant.USER_ID_REQUEST_HEADER);
            String tempId = request.getHeader(RedisConstant.TEMP_USER_ID_HEADER);

            //4、给 template 中添加上老请求的请求头
            if(!StringUtils.isEmpty(userId)){
                template.header(RedisConstant.USER_ID_REQUEST_HEADER,userId);
            }

            if(!StringUtils.isEmpty(tempId)){
                template.header(RedisConstant.TEMP_USER_ID_HEADER,tempId);
            }
            //给当前请求模板把请求头添上
        }



    }
}
